package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;

import java.time.Period;

import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.core.util.StrUtil;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;

import com.zzyl.nursing.utlis.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;

import org.apache.poi.ss.formula.functions.Columns;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderServiceImpl elderServiceImpl;

    @Autowired
    private BedServiceImpl bedServiceImpl;

    @Autowired
    private ContractServiceImpl contractServiceImpl;

    @Autowired
    private CheckInServiceImpl checkInServiceImpl;

    @Autowired
    private CheckInConfigServiceImpl checkInConfigServiceImpl;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     *   申请入住
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyCheckIn(CheckInApplyDto dto) {
        //判断老人是否已经入住  select * from elder where id_card_no = ? and status = 1
        //根据id查到老人信息
        Elder elder = elderServiceImpl.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .one();
        if (elder != null && elder.getStatus() == 1){
            //说明老人已经入住了
            throw new RuntimeException("该老人已经入住了");
        }
        //更改床位状态为已入住
        Bed bed = new Bed();
        bed.setId(dto.getCheckInConfigDto().getBedId());
        Bed bed1 = bedServiceImpl.getById(dto.getCheckInConfigDto().getBedId());
        bed.setBedNumber(bed1.getBedNumber());
        bed.setBedStatus(1);
        bedServiceImpl.updateById(bed);
        //新增或者更新老人
        Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
//        newElder.setId(elder.getId());
        newElder.setStatus(1);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());
        elderServiceImpl.saveOrUpdate(newElder);
        //新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(newElder.getId());

        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contract.setElderName(newElder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getFeeStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getFeeEndDate());
        //判断当前时间和生效时间  如果当前时间在入住时间之后  那么状态则为已生效
        LocalDateTime now = LocalDateTime.now();
        contract.setStatus(now.isAfter(dto.getCheckInConfigDto().getFeeStartDate())?1:0);
        contractServiceImpl.save(contract);
        //新增入住信息
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(newElder.getId());
        checkIn.setElderName(newElder.getName());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        //判断当前时间和入住时间  如果当前时间在入住时间之后  那么状态则为已入住
        checkIn.setStatus(now.isAfter(dto.getCheckInConfigDto().getEndDate())?1:0);
        checkInServiceImpl.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigServiceImpl.save(checkInConfig);

    }

    /**
     * 根据入住id查询入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        // 先初始化内部的VO对象
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Contract contract1 = new Contract();
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();

        // 设置到checkInDetailVo中
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract1);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        // 查询入住信息
        CheckIn checkIn = checkInServiceImpl.getById(id);
             //拿到入住信息的床位
             String bedNumber = checkIn.getBedNumber();

        //根据床位查询老人信息
        Elder elder = elderServiceImpl.lambdaQuery()
                .eq(Elder::getBedNumber, bedNumber)
                .one();
        BeanUtil.copyProperties(elder,checkInElderVo );
        //计算出来老人年龄
        String birthday = elder.getBirthday();
        // 解析生日字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate birthDate = LocalDate.parse(birthday, formatter);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算年龄
        int age = currentDate.getYear() - birthDate.getYear();
        if (currentDate.isBefore(birthDate.withYear(currentDate.getYear()))) {
            age--;
        }
        checkInElderVo.setAge(age);

        // 根据老人的id查询合同
        Contract contract = contractServiceImpl.lambdaQuery()
                .eq(Contract::getElderId, elder.getId())
                .one();
        BeanUtil.copyProperties(contract, contract1);

        //查询入住配置
        CheckInConfig checkInConfig = checkInConfigServiceImpl.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId())
                .one();
        BeanUtil.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setStartDate(checkIn.getStartDate());

       //转换家属列表
        String remark = checkIn.getRemark();
        if (StrUtil.isNotBlank(remark)) {
            // 使用 parseArray 而不是 parseObj，因为这是数组格式
            JSONArray jsonArray = JSONUtil.parseArray(remark);
            for (int i = 0; i < jsonArray.size(); i++) {
                // 获取数组中的每个JSON对象
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                // 创建ElderFamilyVo对象并设置属性
                ElderFamilyVo elderFamilyVo = new ElderFamilyVo();
                elderFamilyVo.setKinship(jsonObject.getStr("kinship"));
                elderFamilyVo.setName(jsonObject.getStr("name"));
                elderFamilyVo.setPhone(jsonObject.getStr("phone"));
                elderFamilyVoList.add(elderFamilyVo);
            }
        }
        return checkInDetailVo;
    }
}
